package com.heima.comment.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.comment.service.ComentRepayService;
import com.heima.model.comment.dtos.CommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.comment.pojo.ApComment;
import com.heima.model.comment.pojo.ApCommentLike;
import com.heima.model.comment.pojo.ApCommentRepay;
import com.heima.model.comment.pojo.ApCommentRepayLike;
import com.heima.model.comment.vo.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.ApUserThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ComentRepayServiceImpl implements ComentRepayService {

    @Autowired
    MongoTemplate mongoTemplate;


    /**
     * 回复评论时，先加载评论
     * @param dto
     * @return
     */
    //考虑如果中间点赞需要数据回显 TMD....
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        //检查参数
        if (dto==null||dto.getCommentId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getSize()==0||dto.getSize()>50){
            dto.setSize(50);
        }
        if (dto.getMinLikes()==null){
            dto.setMinLikes((long) 0);
        }

        //查询数据
        Query query=Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("updatedTime").gte(dto.getMinLikes()));
        //分页排序查询
        query.limit(dto.getSize()).with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApCommentRepay> commentRepayList = mongoTemplate.find(query, ApCommentRepay.class);

        //判断用户是否登录
        ApUser apUser = ApUserThreadLocalUtils.getUser();
        if (apUser==null||apUser.getId()==0){
            return ResponseResult.okResult(commentRepayList);
        }

        List<String> collect = commentRepayList.stream().map(commentRepay -> commentRepay.getCommentId()).collect(Collectors.toList());
        //如果登录则用户的点赞高亮显示

        Query query2=Query.query(Criteria.where("commentId").in(collect).and("authorId").is(apUser.getId()));
        List<ApCommentLike> apCommentLikes = mongoTemplate.find(query2, ApCommentLike.class);

        ArrayList<ApCommentVo> list1=new ArrayList<>();
        for (ApCommentRepay commentRepay: commentRepayList) {
            ApCommentVo apCommentVo = JSON.parseObject(JSON.toJSONString(commentRepay), ApCommentVo.class);
            for (ApCommentLike commentLike : apCommentLikes) {
                if (commentRepay.getCommentId().equals(apCommentVo.getEntryId())){
                    apCommentVo.setOperation((short) 0);
                    list1.add(apCommentVo);
                    break;
                }
            }
        }
        //返回结果

        return ResponseResult.okResult(list1);
    }

    /**
     * 保存评论回复
     * @param dto
     * @return
     */
    //考虑保存评论需要数据回显  TMD....
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        //检查数据
        if(dto==null||dto.getCommentId()==null||dto.getContent()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //获取登录用户信息
        ApUser apUser = ApUserThreadLocalUtils.getUser();
        if (apUser==null&&apUser.getId()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //保存数据到mongodb
        ApCommentRepay commentRepay = new ApCommentRepay();
        commentRepay.setAuthorId(apUser.getId());
        commentRepay.setAuthorName(apUser.getName());
        commentRepay.setCommentId(dto.getCommentId());
        commentRepay.setContent(dto.getContent());
        commentRepay.setCreatedTime(new Date());
        commentRepay.setLikes(0);
        commentRepay.setUpdatedTime(new Date());
        mongoTemplate.save(commentRepay);

        //修改评论数
        //查询评论列表，修改点赞数
        Query query1=Query.query(Criteria.where("entryId").is(dto.getCommentId()).and("authorId").is(apUser.getId()));
        ApComment comment = mongoTemplate.findOne(query1, ApComment.class);
        comment.setReply(comment.getReply()+1);
        mongoTemplate.save(comment);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 点赞回复
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDto dto) {
        //检查参数
        if (dto==null||dto.getCommentRepayId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取用户信息
        ApUser apUser = ApUserThreadLocalUtils.getUser();
        if (apUser==null||apUser.getId()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }


        Query query=Query.query(Criteria.where("commentRepayId").is(dto.getCommentRepayId()).and("authorId").is(apUser.getId()));
        ApCommentRepayLike commentRepayLike = mongoTemplate.findOne(query, ApCommentRepayLike.class);
        //查询评论列表，修改点赞数
        Query query1=Query.query(Criteria.where("entryId").is(dto.getCommentRepayId()).and("authorId").is(apUser.getId()));
        ApComment comment = mongoTemplate.findOne(query1, ApComment.class);
        //如果没有查询到点赞则创建
        if (commentRepayLike==null){
            commentRepayLike=new ApCommentRepayLike();
            commentRepayLike.setAuthorId(apUser.getId());
            commentRepayLike.setCommentRepayId(dto.getCommentRepayId());
            mongoTemplate.save(commentRepayLike);
            //查询评论的点赞列表加一

            comment.setLikes(comment.getLikes()+1);

        }else {
            //查询数据如果查询到点赞则删除
            mongoTemplate.remove(commentRepayLike);
            //回复评论的点赞减一
            if (comment.getLikes()>=1){
                comment.setLikes(comment.getLikes()-1);
            }
        }

        return ResponseResult.okResult(mongoTemplate.save(comment));
    }
}
